package com.qiangesoft.ratelimit.core.redis;

import com.qiangesoft.ratelimit.core.LimitKeyBuilder;
import com.qiangesoft.ratelimit.core.LimitType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 限流处理
 *
 * @author qiangesoft
 * @date 2024-03-19
 */
@RequiredArgsConstructor
@Slf4j
@Aspect
@Component
public class RedisLimitAspect {

    private final RedisTemplate<Object, Object> redisTemplate;

    private final RedisScript<Long> limitScript;

    @Before("@annotation(redisRateLimit)")
    public void doBefore(JoinPoint point, RedisRateLimit redisRateLimit) {
        LimitType limitType = redisRateLimit.limitType();
        String key = redisRateLimit.key();
        int time = redisRateLimit.time();
        int count = redisRateLimit.count();

        String limitKey = LimitKeyBuilder.build(limitType, key,  point);
        List<Object> keys = Collections.singletonList(limitKey);
        try {
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (number == null || number.intValue() > count) {
                throw new RuntimeException("访问太频繁，请稍后再试！");
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }
}
